package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.user.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * 小程序token验证处理
 *
 * @author ruoyi
 */
@Component
public class ApiTokenService {



    // token自定义标识
    @Value("${api-token.header}")
    private String header;
    // token令牌秘钥
    @Value("${api-token.secret}")
    private String secret;
    // token有效期
    @Value("${api-token.expireTime}")
    private int expireTime;
    // token有效期
    @Value("${api-token.refreshTime}")
    private int refreshTime;

    public String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        // 自定义参数，把需要存入token的参数都可以自定义到这里，比如 角色 部门类的关键参数
        claims.put(Constants.USER_ID, user.getId());
        return doGenerateToken(claims, user.getNickname());
    }

    /**
     * 生成小程序token
     *
     * @param claims
     * @param subject
     * @return
     */
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = new Date();
        final Date expirationDate = calculateExpirationDate(createdDate);
        return Jwts.builder()
                .setClaims(claims) // 存入自定义参数
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 计算过期时间
     *
     * @param createdDate
     * @return
     */
    private Date calculateExpirationDate(Date createdDate) {
        return DateUtils.addSeconds(createdDate, expireTime);
    }

    /**
     * 判断是否在需要刷新token的临界值以内
     *
     * @param expirationDate 过期时间
     * @return
     */
    public Boolean isRefreshToken(Date expirationDate) {
        //判断是否过期
        if (expirationDate.getTime() <= System.currentTimeMillis()) {
            return false;
        }
        //间隔时间
        long intervalSeconds = (expirationDate.getTime() - System.currentTimeMillis()) / 1000;
        return intervalSeconds <= refreshTime;
    }

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    public Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

}
